package com.fingard.dsp.bank.directbank.jrtt01;

import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBalance;
import com.fingard.dsp.bank.reqrespobj.balance.Req7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsBalDetail;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsHisBalDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * 财经-海外接口
 */
public class JRTT01Balance extends JRTT01Base implements IBalance{

    /**
     * 查询余额
     * @param p_req7506
     * @return
     * @throws Exception
     */
    @Override
    public RetAts7506BalQry d_7506_BalQry(Req7506BalQry p_req7506) throws Exception{
        RetAts7506BalQry retAts7506BalQry = new RetAts7506BalQry(p_req7506.reqHeader);
        retAts7506BalQry.writeStart();
        try{
            while (p_req7506.readRecord()) {
                RetAtsBalDetail detail = new RetAtsBalDetail();
                //非公有参数
                XmlTextWriter xmlTextWriter = new XmlTextWriter();
                //拼接请求报文头
                JRTT01Header header=new JRTT01Header();
                header.requestType="account.060.001.03";//交易码
                header.msgId=getQryTransID();
                writeCommonHeader(xmlTextWriter,header);
                xmlTextWriter.writeEndElement();
                //拼接请求报文体
                xmlTextWriter.writeStartElement("ReqDetail");
                xmlTextWriter.writeElementStringWithoutTransfer("QueryType","BALI");//实时余额
                xmlTextWriter.writeElementStringWithoutTransfer("BankType", p_req7506.readedDetail.bankType);//银行体系
                xmlTextWriter.writeElementStringWithoutTransfer("PayAccount", p_req7506.readedDetail.actNum);//付款帐号
                xmlTextWriter.writeElementStringWithoutTransfer("PayIBAN", p_req7506.readedDetail.payIBAN);//付款IBAN账号
                //查询时间日期
                Calendar tmpCalendarFrom = Calendar.getInstance();
                tmpCalendarFrom.setTime(Format.DateTimeFormat.parse(Format.DateTimeFormat.format(new Date())));
                xmlTextWriter.writeElementStringWithoutTransfer("FrDt", getGlobalLocalDate(tmpCalendarFrom.getTime(),p_req7506.readedDetail.timeZone));//该日期为账户时区的当日日期
                xmlTextWriter.writeElementStringWithoutTransfer("ToDt", Format.Date10Format.format(new Date()));//该日期为输入日期
                xmlTextWriter.writeElementStringWithoutTransfer("TimeZone", p_req7506.readedDetail.timeZone);//时差
                xmlTextWriter.writeEndElement();
                xmlTextWriter.writeEndDocument();
                //发送请求报文
                String[] bankResult = sendToBank(xmlTextWriter.toXmlString(),"swift");
                //处理响应报文
                if (bankResult[0].length() == 0) {
                    StringBuilder tmpSb = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSb);
                    if (tmpBkReader != null) {
                        String returnCode = tmpBkReader.getFirstText("/Document/Response/GrpHdr/ResponseStatus").trim();//返回码
                        String returnMsg = tmpBkReader.getFirstText("/Document/Response/GrpHdr/AddtlInf");//返回信息
                        if("ACCP".equals(returnCode)){
                            detail.actNum = tmpBkReader.getFirstText("/Document/Response/ReqDetail/PayAccount");//账号
                            while (tmpBkReader.read("/Document/Response/Rpt/Bal")){
                                XElement readXElement = tmpBkReader.readedXElement;
                                detail.respCode = "0";//响应码
                                detail.respInfo = returnMsg;//响应信息
                                detail.actCur = convertCurToATS(readXElement.getSingleChild("Amt").getAttrValue("Ccy"));//币种
                                detail.availBal = readXElement.getSingleTextNotNull("AvaiAmt");//可用余额
                                detail.currBal = readXElement.getSingleTextNotNull("Amt");//余额
                            }
                        }else{
                            detail.respCode = "-1";
                            detail.respInfo = returnMsg;
                        }
                    }else{
                        detail.respCode = "-1";
                        detail.respInfo = tmpSb.toString();
                    }
                }else{
                    detail.respCode = "-1";
                    detail.respInfo = bankResult[1];
                }
                retAts7506BalQry.writeRetDetail(detail, p_req7506.isBatch);
            }
        }catch (Exception e){
            WriteBankLogLn("查询余额异常"+e);
            retAts7506BalQry.writeRespCode("-1");
            retAts7506BalQry.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts7506BalQry.writeEnd();
        return retAts7506BalQry;
    }

    @Override
    public RetAts7505HisBalQry d_7505_BalQry(Req7505HisBalQry p_req7505) throws Exception{
        //增加历史明细支持查询日期
        if(StringHelper.hasAnyChar(getBankConfig().getValueAsString("hisTransSupDate"))
                && getBankConfig().getValueAsString("hisTransSupDate").length()==8){
            //判断起始日
            Date avaiDate = Format.Date8Format.parse(getBankConfig().getValueAsString("hisTransSupDate"));
            Date startDate = Format.Date8Format.parse(p_req7505.dateFrom);
            Date endDate = Format.Date8Format.parse(p_req7505.dateTo);
            if(endDate.after(avaiDate)){
                if(startDate.before(avaiDate)){
                    p_req7505.dateFrom=getBankConfig().getValueAsString("hisTransSupDate");
                }
            }else{
                p_req7505.dateFrom=getBankConfig().getValueAsString("hisTransSupDate");
                p_req7505.dateTo=getBankConfig().getValueAsString("hisTransSupDate");
            }
        }
        RetAts7505HisBalQry retAts = new RetAts7505HisBalQry(p_req7505.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try{
            //非公有参数
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            //拼接请求报文头
            JRTT01Header header=new JRTT01Header();
            header.requestType="account.060.001.03";//交易码
            header.msgId=getQryTransID();
            writeCommonHeader(xmlTextWriter,header);
            xmlTextWriter.writeEndElement();
            //拼接请求报文体
            xmlTextWriter.writeStartElement("ReqDetail");
            xmlTextWriter.writeElementStringWithoutTransfer("QueryType","BALH");//历史余额
            xmlTextWriter.writeElementStringWithoutTransfer("BankType", p_req7505.bankType);//银行体系
            xmlTextWriter.writeElementStringWithoutTransfer("PayAccount", p_req7505.actNum);//付款帐号
            xmlTextWriter.writeElementStringWithoutTransfer("PayIBAN", p_req7505.payIBAN);//付款行SwiftCode
            xmlTextWriter.writeElementStringWithoutTransfer("FrDt", DateHelper.convertD8toD10(p_req7505.dateFrom));//该日期为输入日期
            xmlTextWriter.writeElementStringWithoutTransfer("ToDt", DateHelper.convertD8toD10(p_req7505.dateTo));//该日期为输入日期
            xmlTextWriter.writeElementStringWithoutTransfer("TimeZone", p_req7505.timeZone);//时差
            xmlTextWriter.writeEndElement();
            xmlTextWriter.writeEndDocument();
            //发送请求报文
            String[] bankResult = sendToBank(xmlTextWriter.toXmlString(),"swift");
            //处理响应报文
            if (bankResult[0].length() == 0) {
                StringBuilder tmpSb = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSb);
                if (tmpBkReader != null) {
                    String returnCode = tmpBkReader.getFirstText("/Document/Response/GrpHdr/ResponseStatus").trim();//返回码
                    String returnMsg = tmpBkReader.getFirstText("/Document/Response/GrpHdr/AddtlInf");//返回信息
                    if("ACCP".equals(returnCode)){
                        while (tmpBkReader.read("/Document/Response/Rpt/Bal")) {
                            RetAtsHisBalDetail tmpRetDetail = new RetAtsHisBalDetail();
                            tmpRetDetail.actBal = tmpBkReader.readedXElement.getSingleTextNotNull("Amt");//历史余额
                            tmpRetDetail.availBal = tmpBkReader.readedXElement.getSingleTextNotNull("AvaiAmt");//历史可用余额
                            tmpRetDetail.balDate = DateHelper.convertD8toD10(tmpBkReader.readedXElement.getSingleChild("Dt").getSingleTextNotNull("Dt"));//余额时间
                            retAts.writeRetDetail(tmpRetDetail);
                        }
                    }else{
                        tmpRespCode = "-1";
                        tmpRespInfo = returnMsg;
                    }
                }else{
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpSb.toString();
                }
            }else{
                tmpRespCode = "-1";
                tmpRespInfo = bankResult[1];
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if (tmpRespCode.equals("-1")) {
            retAts = new RetAts7505HisBalQry(p_req7505.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("返回结果为空，所查询时间段内不存在历史余额");
        }
        retAts.writeEnd();
        return retAts;
    }
}
